package cn.bugDance.domain.security.servive.login;


import cn.bugDance.domain.security.model.entity.UserIdOpenIdEntity;
import cn.bugDance.domain.security.repository.ISecurityRepository;
import cn.bugDance.domain.security.servive.IWeiXinLoginService;
import cn.bugDance.domain.security.servive.adapter.IWeiXinLoginAdapter;
import cn.bugDance.domain.security.servive.shiro.JwtUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Service
public class WeiXinLoginService implements IWeiXinLoginService {

    @Resource
    private ISecurityRepository securityRepository;

    @Resource
    private IWeiXinLoginAdapter weiXinLoginAdapter;

    @Override
    public String createQrCodeTicket() {
        return weiXinLoginAdapter.createQrCodeTicket();
    }

    @Override
    public void createJwtToken(String ticket, String openId) {
        UserIdOpenIdEntity userIdOpenIdEntity = securityRepository.queryUserIdOpenIdEntityByOpenId(openId);
        JwtUtil jwtUtil = new JwtUtil();
        Map<String, Object> chaim = new HashMap<>();
        chaim.put("openId", openId);
        chaim.put("userId", userIdOpenIdEntity == null ? null : userIdOpenIdEntity.getUserId());

        String jwtToken = jwtUtil.encode(openId, 60 * 60 * 1000, chaim);
        securityRepository.saveJwtToken(ticket, jwtToken);
    }

    @Override
    public String checkJwtToken(String ticket) {
        return securityRepository.checkJwtToken(ticket);
    }
}
